import {history, request} from "umi";
import Cookies from 'js-cookie'
import {getUserInfo, ShowError} from "@/utils/format";
import ServiceEnvs from "@/services/ServiceEnvs";
import {message, Upload, UploadProps} from "antd";
import {RcFile} from "antd/es/upload/interface";

const baseUrl = ServiceEnvs.baseUrl

// 1-1-2 学科评估情况
export const DisciEvalSituationApi = (queryString: object) => {
  const userInfo = getUserInfo()
  return request(baseUrl+'/api/index/disci-cons/progress/disci-eval-situation', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: queryString,
  })
}

//学科填报 + 通用 API
export const FillApi = (api, data, success, error, serviceError) => {
  const userInfo = getUserInfo()
  request(baseUrl + api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: data,
  }).then(response => {
    if (response.status === 0) {
      success(response)
    } else {
      error(response)
    }
  }, err => serviceError(err))
}

export const FillApi2 = (api: string, queryString: string) => {
  const userInfo = getUserInfo()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: queryString,
  })
}

// 1-1-3 学科影响力情况
export const DisciInfluenceApi = (queryString: object) => {
  const userInfo = getUserInfo()
  return request(baseUrl+'/api/index/disci-cons/progress/disci-influence', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: queryString,
  })
}

//上传接口
export const UploadApi = (api, success) => {
  const userInfo = getUserInfo()
  const props: UploadProps = {
    name: 'file',
    action: baseUrl+api,
    multiple: true,
    onRemove: false,
    headers: {
      'Authorization': userInfo.token
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log("@uploading", info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        // message.success(`${info.file.name} 文件上传成功`);
        // console.log("@info",info, info.file.response)
        console.log("@info", info)
        success(info)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };
  return props
}

// 上传之前的判断
const beforeUpload = (file: RcFile) => {
  console.log("@@file", file)
  const isJpgOrPng = file.type === 'application/pdf'
  if (!isJpgOrPng) {
    ShowError('仅限pdf文件！')
  }
  const isLt2M = file.size / 1024 / 1024 < 20;
  if (!isLt2M) {
    ShowError('文件大小不能超过20M！')
  }
  if (!(isJpgOrPng && isLt2M)) {
    return Upload.LIST_IGNORE
  }
  return isJpgOrPng && isLt2M;
};

// ***************** 附件功能：上传附件 开始 *****************
export const UploadAttachApi = (api, success, remove) => {
  const userInfo = getUserInfo()
  const props: UploadProps = {
    name: 'file',
    action: baseUrl+api,
    multiple: true,
    headers: {
      'Authorization': userInfo.token
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log("@uploading", info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        // message.success(`${info.file.name} 文件上传成功`);
        // console.log("@info",info, info.file.response)
        console.log("@info", info)
        success(info)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    beforeUpload: beforeUpload,
    onRemove(file) {
      remove(file)
    },
  };
  return props
}

export const SubmitAttachApi = (api, download, path) => {
  const userInfo = getUserInfo()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {"fill_id": download, "path":path}
  })
}
// ***************** 附件功能：上传附件 结束 *****************

// ***************** 附件功能：获取附件列表 开始 *****************
export const GetAttachList = (api: string, id: string, name: string) => {
  const userInfo = getUserInfo()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {"id": id, "name": name ? name : userInfo['discipline_name']}
  })
}
// ***************** 附件功能：获取附件列表 结束 *****************

// ***************** 附件功能：下载文件 开始 *****************
export const DownloadAttachApi = (id: string, name: string, fileName: string) => {
  const userInfo = getUserInfo()
  const api = '/api/attach-filled-download'
  const url = baseUrl+api+'?filename='+fileName+'&id='+id+'&name='+(name ? name : userInfo['discipline_name'])+'&univ_name='+userInfo['univ_name']
  const eleLink = document.createElement('a');
  eleLink.style.display = 'none';
  eleLink.href = url;
  document.body.appendChild(eleLink);
  eleLink.click();
  document.body.removeChild(eleLink);
}
// ***************** 附件功能：下载文件 结束 *****************

// ***************** 台账功能：下载台账 开始 *****************
export const DownloadAllApi = (univ_name: string, discipline_name: string) => {
  const userInfo = getUserInfo()
  const api = '/api/index/school-query/export-all-discipline-table'
  const url = baseUrl+api+'?univ_name='+univ_name+'&discipline_name='+discipline_name
  const eleLink = document.createElement('a');
  eleLink.style.display = 'none';
  eleLink.href = url;
  document.body.appendChild(eleLink);
  eleLink.click();
  document.body.removeChild(eleLink);
}// ***************** 台账功能：下载台账 结束 *****************

// 下载接口
export const DownloadApi = (fileName) => {
  const userInfo = getUserInfo()
  const api = '/api/download'
  const url = baseUrl+api+'?id='+fileName
  const eleLink = document.createElement('a');
  eleLink.style.display = 'none';
  eleLink.href = url;
  document.body.appendChild(eleLink);
  eleLink.click();
  document.body.removeChild(eleLink);
}

// 审核接口
export const SchoolCheckShow = (id, fill_id) => {
  const api = '/api/index/school-query/query-single-discipline-table'
  const userInfo = getUserInfo()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {id:id, fill_id: fill_id}
  })
}

// 查看接口
export const ShowApi = (fill_id: string) => {
  const queryString = new URLSearchParams({fill_id: fill_id}).toString()
  const userInfo = getUserInfo()
  return request(baseUrl+'/api/index/user-query/query-single-table-info', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: queryString,
  })
}

// 审核通过
export const SchoolPass = (id) => {
  const userInfo = getUserInfo()
  const api = "/api/index/school-query/check-single-discipline-current"
  // const queryString = new URLSearchParams({id:id}).toString()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {data_id:[{id: id}]}
  })
}

export const SchoolPassAll = (id_arr) => {
  const userInfo = getUserInfo()
  const api = "/api/index/school-query/check-single-discipline-current"
  // const queryString = new URLSearchParams({id:id}).toString()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {data_id:id_arr}
  })
}

// 审核驳回
export const SchoolReject = (user_fill_id) => {
  const userInfo = getUserInfo()
  const api = "/api/index/school-query/delete-single-discipline-table"
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {user_fill_id: [{id: user_fill_id}]}
  })
}

// 上传word
export const UploadWordPath = (api: string, path = []) => {
  const userInfo = getUserInfo()
  console.log("@请求数据", {path: path})
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {path: path},
  })
}

// 暂存接口
export const SaveApi = (api: string, data: object) => {
  const userInfo = getUserInfo()
  console.log("@API", data)
  // 将Moment转为string
  if (data.data && data.data instanceof Array) {
    console.log("is array", data.data)
    for (let i = 0; i < data.data.length; i++) {
      if (data.data[i] instanceof Object) {
        console.log("is object", data.data[i])
        for (let k in data.data[i]) {
          if (data.data[i][k] instanceof Array) {
            for (const kk in data.data[i][k]) {
              if (data.data[i][k][kk] && data.data[i][k][kk]._isAMomentObject) {
                data.data[i][k][kk] = data.data[i][k][kk]._i
              }
            }
          } else if (data.data[i][k] && data.data[i][k]._isAMomentObject) {
            data.data[i][k] = data.data[i][k]._i
          }
        }
      }
    }
    console.log("转换后的data", data)
  }
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: data
  })
}

// 查看暂存状态
export const GetSaveApi = (api: string, form_id: string) => {
  const userInfo = getUserInfo()
  return request(baseUrl+api, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {fill_id: form_id}
  })
}

// 查看可下载文件
export const GetUploadedFiles = (api: string, id: string) => {
  const userInfo = getUserInfo()
  const queryString = new URLSearchParams({id: id}).toString()
  console.log(baseUrl+api+"?"+queryString)
  return request(baseUrl+api+"?"+queryString, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
      'Authorization': userInfo.token
    },
  })
}

// 无数据提交
export const NoDataAPI = (id: string) => {
  const userInfo = getUserInfo()
  return request(baseUrl+"/api/index/disci-cons/fill-empty", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Authorization': userInfo.token
    },
    data: {fill_id: id}
  })
}
